#include "imu_data.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    // 设置随机数种子
    srand((unsigned int)time(NULL));
    
    // 生成示例 IMU 数据
    const int NUM_SAMPLES = 100;
    ImuData *imu_data = (ImuData *)malloc(sizeof(ImuData) * NUM_SAMPLES);
    
    if (imu_data == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    
    printf("Generating %d IMU data samples...\n", NUM_SAMPLES);
    for (int i = 0; i < NUM_SAMPLES; i++) {
        imu_data[i] = read_imu_data();
        // 稍微延迟以模拟实际的数据采集间隔
        for (volatile int j = 0; j < 100000; j++);
    }
    
    // 将数据写入 CSV 文件
    const char *csv_filename = "imu_data.csv";
    if (write_imu_data_to_csv(csv_filename, imu_data, NUM_SAMPLES) == 0) {
        printf("IMU data has been successfully written to file %s\n", csv_filename);
    }
    
    // 释放原始数据内存
    free_imu_data(imu_data);
    
    // 从 CSV 文件读取数据
    ImuData *read_data;
    int read_samples;
    if (read_imu_data_from_csv(csv_filename, &read_data, &read_samples) == 0) {
        printf("Successfully read %d samples from %s\n", read_samples, csv_filename);
        
        // 打印前5个样本以验证
        printf("\nFirst 5 sample data:\n");
        printf("Timestamp\t\tAccel_X\t\tAccel_Y\t\tAccel_Z\t\tGyro_X\t\tGyro_Y\t\tGyro_Z\n");
        for (int i = 0; i < (read_samples < 5 ? read_samples : 5); i++) {
            printf("%.6lf\t%.6lf\t%.6lf\t%.6lf\t%.6lf\t%.6lf\t%.6lf\n",
                   read_data[i].timestamp,
                   read_data[i].accel_x, read_data[i].accel_y, read_data[i].accel_z,
                   read_data[i].gyro_x, read_data[i].gyro_y, read_data[i].gyro_z);
        }
        
        // 释放读取的数据内存
        free_imu_data(read_data);
    }
    
    printf("\nProgram execution completed\n");
    return 0;
}